package gui.beans;

import java.awt.event.ActionEvent;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JFormattedTextField;

import gui.eventos.UpdateIntegerEvent;
import gui.eventos.UpdateIntegerListener;

public class MyIntegerField extends JFormattedTextField {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2972131006544623707L;

	private List<UpdateIntegerListener> listeners = null;

	public MyIntegerField() {
		super(new Integer(0));

		this.setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);

		this.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent actionevent) {
				try {
					commitEdit();
				} catch (ParseException e) {
				}
				transferFocus();
			}
		});

		addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyTyped(java.awt.event.KeyEvent e) {
				cambio = true;
			}
		});

		addFocusListener(new java.awt.event.FocusAdapter() {
			public void focusLost(java.awt.event.FocusEvent e) {
				if (cambio) {
					cambio = false;
					fireUpdateEvent();
				}
			}
		});
	}

	public void addUpdateIntegerListener(UpdateIntegerListener listener) {
		if (listeners == null)
			listeners = new ArrayList<UpdateIntegerListener>();

		listeners.add(listener);
	}

	private void fireUpdateEvent() {
		if (listeners == null)
			return;

		try {
			commitEdit();
		} catch (ParseException e) {
		}

		UpdateIntegerEvent e = new UpdateIntegerEvent(this, ((Integer) getValue()).intValue());
		Iterator<UpdateIntegerListener> it = listeners.iterator();
		while (it.hasNext()) {
			it.next().valueUpdated(e);
		}
	}

	public boolean cambio = false;
}
